<script lang="ts" setup>
import {
  getPatientConsultOrderPreAPI,
  postPatientConsultOrderAPI,
  postPatientConsultPayAPI,
} from '@/apis/consult'
import { getPatientInfoByIdAPI } from '@/apis/subpkg'
import { useConsultStore } from '@/stores/consult'
import type { GetPatientConsultOrderPreData } from '@/types/consult'
import type { GetPatientMylistItem } from '@/types/subpkg'
import { ref } from 'vue'
import type { CustomPaymentInstance } from '@/types/global-components'
// 获取问诊参数 store
const store = useConsultStore()

// 1. 获取问诊预支付信息
const orderPreInfo = ref<GetPatientConsultOrderPreData>()
const getOrderPre = async () => {
  const res = await getPatientConsultOrderPreAPI({
    type: store.type,
    illnessType: store.illnessType,
  })
  orderPreInfo.value = res.data
}
getOrderPre()

// 2. 获取患者信息
const patientInfo = ref<GetPatientMylistItem>()
const getPatientInfo = async () => {
  const res = await getPatientInfoByIdAPI(store.patientId)
  patientInfo.value = res.data
}
getPatientInfo()

// 3. 立即支付
// 保存订单ID
const orderId = ref('')
const handlePay = async () => {
  // 如果订单ID存在，则不能重复创建
  if (orderId.value) {
    return uni.showToast({ title: '订单不能重复创建！', icon: 'error' })
  }
  const res = await postPatientConsultOrderAPI({
    type: Number(store.type), // 问诊类型
    illnessType: Number(store.illnessType), // 医院：0普通 1三甲
    depId: store.depId, // 科室id
    patientId: store.patientId, // 患者id
    illnessDesc: store.illnessInfo.illnessDesc, // 病情描述
    illnessTime: store.illnessInfo.illnessTime, // 病情时间
    consultFlag: store.illnessInfo.consultFlag, // 是否就诊过
    pictures: store.illnessInfo.pictures, // 图片集合，只要有 {id, url} 即可
  })
  // 接收订单ID
  orderId.value = res.data.id
  // 清空 store 数据，临时注释掉，方便测试弹窗
  // store.reset()
  // 打开自定义支付弹窗(鼠标悬停，能识别到自己写的注释提示)
  customPaymentRef.value?.open()
}

// 4. 自定义支付弹窗
const customPaymentRef = ref<CustomPaymentInstance>()

/** 关闭支付弹窗 */
const handleClose = async () => {
  // 二次确认提示
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
  })
  // 如果用户选择关闭，则关闭支付弹窗
  if (res.cancel) {
    customPaymentRef.value?.close?.()
  }
}

// 确认支付
const handleConfirm = async (index: number) => {
  if (index === 0) {
    uni.showToast({ title: '微信支付暂不支持', icon: 'none' })
    // #ifdef MP-WEIXIN
    // 本质还是发送网络请求，获取后端返回的参数
    // 调用微信支付的 API (SDK方法)
    // wx.requestPayment(传入后端返回的支付参数)
    // #endif
  } else if (index === 1) {
    console.log(1111)
    // #ifndef MP-WEIXIN
    const res = await postPatientConsultPayAPI({
      orderId: orderId.value,
      paymentMethod: '1',
      // 支付完成，由支付宝打开问诊室页面，所以页面路径要完整，从 http 开始
      payCallback: 'http://localhost:5173/#/subpkg_consult/pages/room/room',
    })
    console.log('支付宝支付', res.data)

    // 把地址栏的 url 重定向到支付宝支付付款页面
    location.href = res.data.payUrl
    // #endif
  }
}

// 6.切换支付方式
const handleChange = (index: number) => {
  console.log('切换支付方式', index)
}
</script>

<template>
  <scroll-view>
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${orderPreInfo?.payment || '--'} 元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${orderPreInfo?.couponDeduction ?? ''}`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ orderPreInfo?.pointDeduction ?? '' }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{ orderPreInfo?.actualPayment ?? '' }}</view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section title-font-size="32rpx" title-color="#121826" padding="30rpx" title="患者资料">
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray" v-if="patientInfo"
                >{{ patientInfo?.name }} | {{ patientInfo?.genderValue }} |
                {{ patientInfo?.age }}岁</view
              >
            </template>
          </uni-list-item>
          <uni-list-item border title="病情描述" :note="store.illnessInfo.illnessDesc" />
        </uni-list>
      </uni-section>

      <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view>
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ orderPreInfo?.payment }}</text>
      </view>
      <button class="uni-button" @click="handlePay">立即支付</button>
    </view>
    <!-- 自定义支付弹窗 -->
    <custom-payment
      ref="customPaymentRef"
      :order-id="orderId"
      v-if="orderPreInfo?.payment"
      :amount="orderPreInfo?.payment"
      @close="handleClose"
      @confirm="handleConfirm"
      @change="handleChange"
    />
  </scroll-view>
</template>

<style lang="scss">
@import './index.scss';
</style>
